<?php

namespace App\Admin\Service\Base;


use App\Admin\Service\AbstractAdminService;
use App\Admin\Service\Traits\DestroyServiceTrait;
use App\Admin\Service\Traits\StoreServiceTrait;
use App\Admin\Service\Traits\UpdateServiceTrait;
use App\Common\Exception\ApiMessageException;
use App\Common\Model\Base\Role;
use App\Common\Util\EasySearch;
use App\Common\Util\EasySearchMacro\GlobalSearch;
use Psr\SimpleCache\InvalidArgumentException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * Class RoleService
 */
class RoleService extends AbstractAdminService
{
    use StoreServiceTrait, UpdateServiceTrait, DestroyServiceTrait;

    public function __construct()
    {
        $this->model = new Role();
    }

    /**
     * @return array
     * @throws \Exception
     */
    public function lists(): array
    {
        $query = $this->model->alias('role')->field(["role.id","role.name","role.describe","role.create_time"]);

        return EasySearch::create($query)->addMacro(GlobalSearch::class, "role.name")->getData();
    }

    /**
     * @param int $id
     * @param array $routeIds
     * @return void
     * @throws ApiMessageException
     * @throws \Throwable
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function savePermission(int $id, array $routeIds): void
    {
        $role = Role::find($id);

        if (!$role) {
            throw new ApiMessageException('角色信息错误');
        }

        $role->route_ids = $routeIds;
        $role->save();

        RolePermissionsService::aop()->cacheRoleRouteIds(true);
    }

}
